//
//  RanTool.m
//  shakalaka
//
//  Created by Ran on 15/8/18.
//  Copyright (c) 2015年 Justice. All rights reserved.
//

#import "RanTool.h"
#import "UIImage+YYAdd.h"
#import "SDWebImageManager.h"
#import <Photos/Photos.h>
#import <AVFoundation/AVFoundation.h>
#import <Contacts/Contacts.h>
#import <UserNotifications/UserNotifications.h>
#import <CoreLocation/CoreLocation.h>
#import <AFNetworkReachabilityManager.h>
#import "RBAppDelegateHelper.h"
#import "RBAppDelegateHelper.h"
#import "RBPersistence.h"
#import "RBAccountManager.h"
#import "NSString+RBAdd.h"
#import "UIView+RBAdd.h"
#import <UIColor+YYAdd.h>
#import "UIImageView+RBAdd.h"

static NSString *const ATT_FONT = @"ATT_FONT";
static NSString *const ATT_COLOR = @"ATT_COLOR";
static NSString *const ATT_STRING = @"ATT_STRING";
static NSString *const ATT_LINE_SPACING = @"ATT_LINE_SPACING";
static NSString *const ATT_UNDER_LINE_HEIGHT = @"ATT_UNDER_LINE_HEIGHT";
static NSString *const ATT_UNDER_LINE_COLOR = @"ATT_UNDER_LINE_COLOR";
static NSString *const ATT_THROUGH_LINE_HEIGHT = @"ATT_THROUGH_LINE_HEIGHT";
static NSString *const ATT_THROUGH_LINE_COLOR = @"ATT_THROUGH_LINE_COLOR";

@implementation NSMutableArray(RanAttributeString)

- (void)addAttributeStringWithFont:(UIFont *)font color:(UIColor *)color string:(NSString *)string
{
    [self addObject:@{ATT_FONT: (font? font: [UIFont systemFontOfSize:15]), ATT_COLOR: (color? color: [UIColor blackColor]), ATT_STRING: (string? string: @"")}];
}

- (void)addAttributeStringWithFont:(UIFont *)font color:(UIColor *)color string:(NSString *)string lineSpacing:(CGFloat)spacing
{
    [self addObject:@{ATT_FONT: (font? font: [UIFont systemFontOfSize:15]), ATT_COLOR: (color? color: [UIColor blackColor]), ATT_STRING: (string? string: @""), ATT_LINE_SPACING: @(spacing)}];
}

- (void)addAttributeStringWithFont: (UIFont *)font color: (UIColor *)color string: (NSString *)string lineSpacing: (CGFloat)spacing underLineHeight: (CGFloat)underLineHeight underLineColor: (UIColor *)underLineColor
{
    [self addObject:@{ATT_FONT: (font? font: [UIFont systemFontOfSize:15]), ATT_COLOR: (color? color: [UIColor blackColor]), ATT_STRING: (string? string: @""), ATT_LINE_SPACING: @(spacing),ATT_UNDER_LINE_HEIGHT:@(underLineHeight), ATT_UNDER_LINE_COLOR:underLineColor}];
}

- (void)addAttributeStringWithFont: (UIFont *)font color: (UIColor *)color string: (NSString *)string lineSpacing: (CGFloat)spacing througnLineHeight: (CGFloat)througnLineHeight throughLineColor: (UIColor *)throughLineColor
{
    [self addObject:@{ATT_FONT: (font? font: [UIFont systemFontOfSize:15]), ATT_COLOR: (color? color: [UIColor blackColor]), ATT_STRING: (string? string: @""), ATT_LINE_SPACING: @(spacing),ATT_THROUGH_LINE_HEIGHT:@(througnLineHeight), ATT_THROUGH_LINE_COLOR:throughLineColor}];
}

- (void)addAttributeStringWithImage:(UIImage *)image imageFrame:(CGRect)frame{
    
    NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
    attachment.image = image;
    attachment.bounds = frame;
    [self addObject:attachment];
}

- (void)addAttributeStringWithImage:(UIImage *)image imageSize:(CGSize)imageSize maxFont:(UIFont *)maxFont
{
    NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
    attachment.image = image;
    CGFloat y = 0;
    CGFloat lineH = maxFont.lineHeight;
    CGFloat des = ABS(maxFont.descender);
    y = (lineH - imageSize.height)/2 - des;
    attachment.bounds = CGRectMake(0, y, imageSize.width, imageSize.height);
    [self addObject:attachment];
}

@end

@implementation RanTool

+ (NSAttributedString *)attributeStringMaker:(void (^)(NSMutableArray *))block
{
    NSMutableArray *arrayM = [NSMutableArray array];
    block(arrayM);
    return [self getAttributstringFromArray:arrayM];
}

+ (NSAttributedString *)getAttributstringFromArray:(NSArray *)attributeArray
{
    NSMutableAttributedString *attributeStringM = [[NSMutableAttributedString alloc] init];
    for (NSDictionary *dic in attributeArray)
    {
        if ([dic isKindOfClass:[NSTextAttachment class]])
        {
            NSAttributedString *attributeString = [NSAttributedString attributedStringWithAttachment:(NSTextAttachment *)dic];
            [attributeStringM appendAttributedString:attributeString];
        }else
        {
            NSMutableDictionary *attributeDic = [NSMutableDictionary dictionary];
            [attributeDic setValue:dic[ATT_COLOR] forKey:NSForegroundColorAttributeName];
            [attributeDic setValue:dic[ATT_FONT] forKey:NSFontAttributeName];
            if (dic[ATT_LINE_SPACING])
            {
                NSMutableParagraphStyle *style = [NSMutableParagraphStyle new];
                [style setLineSpacing:[dic[ATT_LINE_SPACING] floatValue]];
                [style setParagraphSpacing:0];
                [attributeDic setValue:style forKey:NSParagraphStyleAttributeName];
            }
            if (dic[ATT_THROUGH_LINE_HEIGHT])
            {
                [attributeDic setValue:@(NSUnderlineStyleSingle) forKey:NSStrikethroughStyleAttributeName];
            }
            if(dic[ATT_THROUGH_LINE_COLOR])
            {
                [attributeDic setValue:dic[ATT_THROUGH_LINE_COLOR] forKey:NSStrokeColorAttributeName];
            }
            if(dic[ATT_UNDER_LINE_HEIGHT])
            {
                [attributeDic setValue:@(NSUnderlineStyleSingle) forKey:NSUnderlineStyleAttributeName];
            }
            if(dic[ATT_UNDER_LINE_COLOR])
            {
                [attributeDic setValue:dic[ATT_UNDER_LINE_COLOR] forKey:NSUnderlineColorAttributeName];
            }
            NSAttributedString *attributeString = [[NSAttributedString alloc] initWithString:dic[ATT_STRING] attributes:attributeDic];
            [attributeStringM appendAttributedString:attributeString];
        }
    }
    return attributeStringM;
}

+ (BOOL)regWithRegString:(NSString *)regString string:(NSString *)string
{
    NSPredicate *reg = [NSPredicate predicateWithFormat:@"SELF MATCHES  %@", regString];
    if ([reg evaluateWithObject:string])
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

+ (NSString *)fillNumString: (NSString *)numString
{
    NSMutableString *stringM = [NSMutableString stringWithCapacity:11];
    for (NSInteger i = 0; i < 11; i++)
    {
        char num = '\0';
        if (numString.length > i)
        {
            num = [numString characterAtIndex:i];
        }
        else
        {
            num = '3';
        }
        [stringM appendFormat:@"%@", [NSString stringWithFormat:@"%c", num]];
    }
    return stringM;
}

+ (NSString *)notNilString:(NSString *)string
{
    return string? string: @"";
}

+ (CGSize)sizeWithAttText:(NSAttributedString *)text
{
    return [self sizeWithAttText:text consSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX)];
}

+ (CGSize)sizeWithAttText:(NSAttributedString *)text consSize:(CGSize)size
{
    CGSize calSize = [text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:NULL].size;
    return CGSizeMake(calSize.width + 2, calSize.height + 2);
}

+ (CGSize)sizeWithText:(NSString *)text consSize:(CGSize)size font:(UIFont *)font
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
    return [text sizeWithFont:font constrainedToSize:size];
#pragma clang diagnostic pop
}

+ (UIEdgeInsets)safeEdge
{
    if (@available(iOS 11.0, *)){
        return UIApplication.sharedApplication.keyWindow.safeAreaInsets;
    };
    return UIEdgeInsetsZero;
}

+ (CGFloat)safeBottomHeight
{
    return [self safeEdge].bottom;
}

+ (UILabel *)labelWithFontSize: (CGFloat)fontSize weight:(NSInteger)weight color: (id)color align:(NSTextAlignment)align text: (NSString *)text
{
    return [self labelWithFontSize:fontSize weight:weight color:color align:align text:text bgColor:nil radius:0];
}

+ (UILabel *)labelWithFontSize: (CGFloat)fontSize weight:(NSInteger)weight color: (id)color align:(NSTextAlignment)align text: (NSString *)text bgColor: (id)bgColor radius: (CGFloat)radius
{
    UILabel *view = UILabel.new;
    UIFontWeight fontWeight;
    if(weight == 0)
    {
        fontWeight = UIFontWeightRegular;
    }
    else if(weight == 1)
    {
        fontWeight = UIFontWeightMedium;
    }
    else
    {
        fontWeight = UIFontWeightHeavy;
    }
    view.font = [UIFont systemFontOfSize:fontSize weight:fontWeight];
    if([color isKindOfClass:UIColor.class])
    {
        view.textColor = (UIColor *)color;
    }
    else if([color isKindOfClass:NSString.class])
    {
        view.textColor = [UIColor colorWithHexString:color];
    }
    view.textAlignment = align;
    view.text = text;
    if (bgColor)
    {
        if([bgColor isKindOfClass:UIColor.class])
        {
            view.backgroundColor = (UIColor *)bgColor;
        }
        else if([bgColor isKindOfClass:NSString.class])
        {
            view.backgroundColor = [UIColor colorWithHexString:bgColor];
        }
    }
    if(radius)
    {
        [view rbSetCornerRadius:radius];
    }
    return view;
}

+ (UILabel *)labelWithFontSize: (CGFloat)fontSize weight:(NSInteger)weight color: (id)color align:(NSTextAlignment)align text: (NSString *)text bgColor: (id)bgColor radius: (CGFloat)radius borderWidth: (CGFloat)borderWidth borderColor: (id)borderColor lines: (NSInteger)lines linePadding: (CGFloat)linePadding hPriority: (NSInteger)hPriority;

{
    UILabel *view = UILabel.new;
    UIFontWeight fontWeight;
    if(weight == 0)
    {
        fontWeight = UIFontWeightRegular;
    }
    else if(weight == 1)
    {
        fontWeight = UIFontWeightMedium;
    }
    else
    {
        fontWeight = UIFontWeightHeavy;
    }
    UIFont *font = [UIFont systemFontOfSize:fontSize weight:fontWeight];
    UIColor *textColor;
    if([color isKindOfClass:UIColor.class])
    {
        textColor = (UIColor *)color;
    }
    else if([color isKindOfClass:NSString.class])
    {
        textColor = [UIColor colorWithHexString:color];
    }
    view.numberOfLines = lines;
    view.attributedText = [RanTool attributeStringMaker:^(NSMutableArray *maker) {
        [maker addAttributeStringWithFont:font color:textColor string:text lineSpacing:linePadding];
    }];
    view.textAlignment = align;
    view.lineBreakMode = NSLineBreakByTruncatingTail;
    if (bgColor)
    {
        if([bgColor isKindOfClass:UIColor.class])
        {
            view.backgroundColor = (UIColor *)bgColor;
        }
        else if([bgColor isKindOfClass:NSString.class])
        {
            view.backgroundColor = [UIColor colorWithHexString:bgColor];
        }
    }
    if(radius)
    {
        [view rbSetCornerRadius:radius];
    }
    if (borderWidth > 0 && borderColor)
    {
        UIColor *color;
        if([borderColor isKindOfClass:UIColor.class])
        {
            color = (UIColor *)borderColor;
        }
        else if([borderColor isKindOfClass:NSString.class])
        {
            color = [UIColor colorWithHexString:borderColor];
        }
        [view rbSetBorderWitdh:borderWidth borderColor:color];
    }
    if (hPriority)
    {
        [view addPriority:hPriority];
    }
    return view;

}

+ (UIImageView *)imgViewWithMode:(NSInteger)mode radius:(CGFloat)radius imgName:(NSString *)imgName
{
    UIImageView *view = UIImageView.new;
    view.clipsToBounds = YES;
    view.contentMode = mode;
    if(radius > 0)
    {
        [view rbSetCornerRadius:radius];
    }
    if([imgName hasPrefix:@"http"] || [imgName hasPrefix:@"upload"])
    {
        [view setImageWithUrl:imgName placeHolder:nil];
    }
    else if(imgName.length)
    {
        view.image = [UIImage imageNamed:imgName];
    }
    return view;
}

+ (NSDecimalNumber *)decimalNumberWithNum: (id)num
{
    if([num isKindOfClass:NSString.class])
    {
        return [NSDecimalNumber decimalNumberWithString:num];
    }
    else if([num isKindOfClass:NSDecimalNumber.class])
    {
        return num;
    }
    else
    {
        return num;
    }
}

+ (NSString *)num:(id)num plusNum:(id)plusNum
{
    NSDecimalNumber *num1 = [self decimalNumberWithNum:num];
    NSDecimalNumber *num2 = [self decimalNumberWithNum:plusNum];
    return [num1 decimalNumberByAdding:num2].stringValue;
}

+ (NSString *)num:(id)num multiNum:(id)numMul
{
    NSDecimalNumber *num1 = [self decimalNumberWithNum:num];
    NSDecimalNumber *num2 = [self decimalNumberWithNum:numMul];
    return [num1 decimalNumberByMultiplyingBy:num2].stringValue;
}

+ (NSArray *)dayHourMinuteSecondFromInterval:(NSInteger)interval
{
    if (interval <= 0)
    {
        return @[@"0", @"00", @"00", @"00"];
    }
    NSInteger day = interval/(3600*24);
    interval = interval%(3600*24);
    
    NSInteger hour = interval/(3600);
    interval = interval%3600;
    
    NSInteger minute = interval/60;
    interval = interval%60;
    
    NSInteger second = interval;
    
    return
    @[
    [NSString stringWithFormat:@"%zd", day],
    [NSString stringWithFormat:@"%02zd", hour],
    [NSString stringWithFormat:@"%02zd", minute],
    [NSString stringWithFormat:@"%02zd", second]
    ];
}

+ (NSArray *)priceFromPrice: (NSString *)price
{
    NSMutableArray *components = [NSMutableArray arrayWithArray:[price componentsSeparatedByString:@"."]];
    if(components.count == 0)
    {
        [components addObject:@"0"];
        [components addObject:@"00"];
    }
    else if(components.count == 1)
    {
        [components addObject:@"00"];
    }
    return components;
}

+ (UIFont *)numFontWithSize:(CGFloat)size
{
    UIFont *font = [UIFont fontWithName:@"Helvetica Neue" size:size];
    if(!font)
    {
        font = [UIFont systemFontOfSize:size];
    }
    return font;
}

@end

@implementation RanTool(RBImage)

+ (UIImage *)image: (UIImage *)image withMaxWidth: (CGFloat)maxWidth
{
    UIImage *scaleImage;
    if (image.size.width > maxWidth)
    {
        CGFloat height = maxWidth / image.size.width * image.size.height;
        scaleImage = [image imageByResizeToSize: CGSizeMake(maxWidth, height)];
    }
    else
    {
        scaleImage = image;
    }
    return scaleImage;
}

+ (NSData *)dataFromImage: (UIImage *)image
       compressionQuality: (CGFloat)compressionQuality
{
    return UIImageJPEGRepresentation(image, compressionQuality);
}

+ (NSData *)dataFromImage:(UIImage *)image
{
    return [self dataFromImage:[self image:image withMaxWidth:750] compressionQuality:0.7];
}

+ (NSArray *)dataArrayFromImageArray: (NSArray *)imageArray
{
    NSMutableArray *dataArrayM = [NSMutableArray arrayWithCapacity:imageArray.count];
    for (UIImage *image in imageArray)
    {
        if ([image isKindOfClass:[UIImage class]])
        {
            [dataArrayM addObject:[self dataFromImage:image]];
        }
    }
    return dataArrayM;
}

+ (void)cacheImage:(UIImage *)image withUrl:(NSString *)url
{
    [[SDWebImageManager sharedManager] saveImageToCache:image forURL:[NSURL URLWithString:url]];
}

+ (void)clearImageDiskCacheCompletion:(void (^)(void))completion
{
    [[SDImageCache sharedImageCache] clearDiskOnCompletion:completion];
}

+ (void)saveImageToAlbum: (UIImage *)image completion: (void(^)(BOOL suc, NSError *error))completion
{
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
         [PHAssetChangeRequest creationRequestForAssetFromImage:image];
     } completionHandler:^(BOOL success, NSError * _Nullable error) {
         dispatch_async(dispatch_get_main_queue(), ^{
             if (completion)
             {
                 completion(success, error);
             }
         });
    }];
}

+ (void)downloadImage: (NSString *)imgUrl completion: (void(^)(UIImage *image))completion
{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imgUrl]]];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (completion)
            {
                completion(image);
            }
        });
    });
}

@end

@implementation RanTool(Cell)

+ (RBCellModel *)cellModelWithSection: (NSInteger)section row: (NSInteger)row dataSource: (NSArray *)dataSource
{
    NSArray *arrayM = [self cellModelsWithSection:section dataSource:dataSource];
    return arrayM[row];
}

+ (RBCellModel *)cellModelWithType:(NSInteger)type dataSource: (NSArray *)dataSource
{
    for (NSInteger i = 0; i < dataSource.count; i++)
    {
        NSMutableArray *cellModels = [self cellModelsWithSection:i dataSource:dataSource];
        for (NSInteger j = 0; j < cellModels.count; j++)
        {
            RBCellModel *cellModel = cellModels[j];
            if (cellModel.type == type)
            {
                return cellModel;
            }
        }
    }
    return nil;
}

+ (id)modelWithSection: (NSInteger)section row: (NSInteger)row dataSource: (NSArray *)dataSource
{
    RBCellModel *cellModel = [self cellModelWithSection:section row:row dataSource:dataSource];
    return cellModel.cellData;
}

+ (NSMutableArray *)cellModelsWithSection: (NSInteger)section dataSource: (NSArray *)dataSource
{
    if (dataSource.count > section)
    {
        RBGroupModel *group = dataSource[section];
        NSMutableArray *arrayM = (NSMutableArray *)group.cellModels;
        return arrayM;
    }
    else
    {
        return @[];
    }
}

+ (NSMutableArray *)modelsWithSection:(NSInteger)section dataSource:(NSArray *)dataSource
{
    NSMutableArray *arrayM = [NSMutableArray array];
    NSArray *cellModels = [self cellModelsWithSection:section dataSource:dataSource];
    for (RBCellModel *cellModel in cellModels)
    {
        [arrayM addObject:cellModel.cellData];
    }
    return arrayM;
}

+ (void)addCellModels: (NSArray *)cellModels withSection: (NSInteger)section dataSource: (NSArray *)dataSource
{
    NSMutableArray *arrayM = [self cellModelsWithSection:section dataSource:dataSource];
    [arrayM addObjectsFromArray:cellModels];
}

+ (void)removeModelAtSection: (NSInteger)section row: (NSInteger)row dataSource: (NSArray *)dataSource
{
    NSMutableArray *arrayM = [self cellModelsWithSection:section dataSource:dataSource];
    [arrayM removeObjectAtIndex:row];
}

+ (NSIndexPath *)indexPathWithModel: (id)model dataSource: (NSArray *)dataSource
{
    for (NSInteger i = 0; i < dataSource.count; i++)
    {
        NSMutableArray *cellModels = [self cellModelsWithSection:i dataSource:dataSource];
        for (NSInteger j = 0; j < cellModels.count; j++)
        {
            RBCellModel *cellModel = cellModels[j];
            if (cellModel.cellData == model)
            {
                return [NSIndexPath indexPathForRow:j inSection:i];
            }
        }
    }
    return [NSIndexPath indexPathForRow:0 inSection:0];
}

+ (void)removeModel: (id)model dataSource: (NSArray *)dataSource
{
    NSIndexPath *indexPath = [self indexPathWithModel:model dataSource:dataSource];
    [self removeModelAtSection:indexPath.section row:indexPath.row dataSource:dataSource];
}

@end

@implementation RanTool(Authority)

- (void)a
{
    //https://www.jianshu.com/p/27e57922232b
    //网络状态
    {
//        AFNetworkReachabilityManager *
    }
    //相册
    {
        PHAuthorizationStatus *status = [PHPhotoLibrary authorizationStatus];
    }
    //相机
    {
        AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        //AVMediaTypeVideo 相机
        //AVMediaTypeAudio 麦克风
    }
    //位置
    {
        CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
//        [CLLocationManager locationServicesEnabled];
    }
    //通讯录
    {
        [CNContact new];
    }
    //通知
    {
        
        UIUserNotificationSettings *settings = [[UIApplication sharedApplication] currentUserNotificationSettings];
    }
}

@end

@implementation RanTool(System)

+ (void)systemShareWithText: (NSString *)text
                      image: (UIImage *)image
                        url: (NSString *)url
                 completion: (UIActivityViewControllerCompletionWithItemsHandler)completion;
{
    NSArray *activityItems = @[[NSURL URLWithString:url],text,image];
    /*
     activities:可以自定义一些操作,出现在分享列表里
     customActivity * customActivit,继承于UIActivity
     activities = @[customActivit,]
     */
    NSArray *activities = nil;
    UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities:activities];
    UIActivityViewControllerCompletionWithItemsHandler block = ^(UIActivityType activityType, BOOL completed, NSArray *returnedItems, NSError *activityError){
        if (completion)
        {
            completion(activityType, completed, returnedItems, activityError);
        }
    };
    activityVC.completionWithItemsHandler = block;
    /** 关闭系统的一些activity类型 */
    activityVC.excludedActivityTypes = @[UIActivityTypeSaveToCameraRoll];
    [[RBAppDelegateHelper keyWindow].rootViewController presentViewController:activityVC animated:YES completion:nil];
}

+ (void)pasteWithText:(NSString *)text
{
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    pasteboard.string = text;
}

+ (void)openSafariWithUrl:(NSString *)url
{
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
}

+ (void)smsWithNumber:(NSString *)number
{
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"sms://%@", number]]];
}

+ (void)telWithNumber:(NSString *)number
{
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"telprompt://%@", number]];
    if (@available(macOS 10.13, iOS 10, *))
    {
        [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {
            
        }];
    }else
    {
        [[UIApplication sharedApplication] openURL:url];
    }
}

+ (void)getStoreVersionWithAppId: (NSString *)appId
                              cn: (BOOL)cn
                      completion: (void(^)(NSString *version, NSString *updateInfo, NSError *error))completion;
{
    NSString *url = @"https://itunes.apple.com/lookup";
    if (cn)
    {
        url = @"https://itunes.apple.com/cn/lookup";
    }
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    request.HTTPMethod = @"POST";
    request.HTTPBody = [[NSString stringWithFormat:@"id=%@&timestamp=%@&ran0=%d&ran1=%d&ran2=%d&ran3=%d",appId, [NSDate date], arc4random_uniform(65535), arc4random_uniform(65535), arc4random_uniform(65535), arc4random_uniform(65535)] dataUsingEncoding:NSUTF8StringEncoding];
    NSURLSession *session = [NSURLSession sharedSession];
    [[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSDictionary *responseObject;
        if(data)
        {
            responseObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        }
        NSString *version = nil;
        NSString *updateInfo = nil;
        if ([responseObject isKindOfClass:[NSDictionary class]])
        {
            NSArray *results = responseObject[@"results"];
            if ([results isKindOfClass:[NSArray class]] && results.count)
            {
                NSDictionary *dic = results.firstObject;
                NSString *storeVersion = dic[@"version"];
                version = storeVersion;
                updateInfo = dic[@"releaseNotes"];
            }
        }
        if (completion)
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                completion(version, updateInfo, error);
            });
        }
    }] resume];
}

+ (void)openStoreWithAppId: (NSString *)appId
{
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"itms-apps://itunes.apple.com/app/id%@", appId]]];
}

+ (void)updateTTC
{
    if (![RBAccountManager ttc])
    {
        [RanTool getStoreVersionWithAppId:kRBAppleID cn: YES completion:^(NSString *version, NSString *updateInfo, NSError *error) {
            if (!error && version.length && [version biggerEqualToVersion:[RBPersistence getProjectVersion]])
            {
                [RBAccountManager setTtc:YES];
            }
            else
            {
                [RanTool getStoreVersionWithAppId:kRBAppleID cn: NO completion:^(NSString *version, NSString *updateInfo, NSError *error) {
                    if (!error && version.length && [version biggerEqualToVersion:[RBPersistence getProjectVersion]])
                    {
                        [RBAccountManager setTtc:YES];
                    }
                }];
            }
        }];
    }
}

+ (void)updateVersionWithHudSuperView:(UIView *)hudSuperView
{
    __weak UIView *weakView = hudSuperView;
    [hudSuperView showProgressWithText:nil];
    
    [RanTool getStoreVersionWithAppId:kRBAppleID cn: YES completion:^(NSString *version, NSString *updateInfo, NSError *error) {
        if (!error && version.length && [version biggerThanVersion:[RBPersistence getProjectVersion]])
        {
            [weakView hideHud];
            [self showUpdateVersionAlertWithVersion:version updateInfo:updateInfo];
        }
        else
        {
            [RanTool getStoreVersionWithAppId:kRBAppleID cn: NO completion:^(NSString *version, NSString *updateInfo, NSError *error) {
                [weakView hideHud];
                if (!error && version.length && [version biggerThanVersion:[RBPersistence getProjectVersion]])
                {
                    [self showUpdateVersionAlertWithVersion:version updateInfo:updateInfo];
                }
                else
                {
                    [weakView showTip:@"未检测到新版本" completion:nil];
                }
            }];
        }
    }];
}

+ (void)showUpdateVersionAlertWithVersion: (NSString *)version updateInfo: (NSString *)updateInfo
{
    UIAlertController *vc = [UIAlertController alertControllerWithTitle:@"检测到新版本,是否前往更新" message:({
        NSString *text = [NSString stringWithFormat:@"v%@ → v%@", [RBPersistence getProjectVersion], version];
        if (updateInfo.length)
        {
            text = [text stringByAppendingString:@"\n"];
            text = [text stringByAppendingString:updateInfo];
        }
        text;
    }) preferredStyle:UIAlertControllerStyleAlert];
    [vc addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [vc addAction:[UIAlertAction actionWithTitle:@"更新" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self openStoreWithAppId:kRBAppleID];
    }]];
    [RBAppDelegateHelper.keyWindow.rootViewController presentViewController:vc animated:YES completion:nil];
}

@end


@implementation RanTool(ScrollView)

+ (void)adjustScrollView:(UIScrollView *)scrollView
{
    if ([scrollView isKindOfClass:UIScrollView.class])
    {
        scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    if ([scrollView isKindOfClass:UITableView.class])
    {
        UITableView *tableView = (UITableView *)scrollView;
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 150000
        if (@available(iOS 15.0, *))
        {
            tableView.sectionHeaderTopPadding = 0;
        }
#endif
    }
    
}

@end
